﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Diagnostics;

namespace PhotoOfTheDay
{
    public partial class Installer : Form
    {
        public Installer()
        {
            InitializeComponent();
        }

        private void Installer_Load(object sender, EventArgs e)
        {
            Updater = new Thread(InstallingThread);
            Updater.Start();
        }

        private Thread Updater;
        private void InstallingThread()
        {
            DateTime StartTime = DateTime.Now;
            SetText UpdateInfo = new SetText(UpdateStatus);

            string MyPath = Application.ExecutablePath;
            string Directory = MyPath.Substring(0, MyPath.LastIndexOf("\\") + 1);
            string Target = Directory + "PhotoOfTheDay.exe";

            string Response = "Removing old files...";
            this.Invoke(UpdateInfo, new Object[] { Response });

            while (File.Exists(Target))
            {
                try
                {
                    File.Delete(Target);
                }
                catch
                {
                    TimeSpan t = DateTime.Now - StartTime;
                    Response = "Waiting for PhotoOfTheDay.exe to close... (" + (int)t.TotalSeconds + ")";

                    if (t.TotalSeconds > 5)
                    {
                        //not stoping automatically, lets force it to stop
                        Process[] processes = Process.GetProcesses();
                        foreach (Process p in processes)
                        {
                            string s = p.ProcessName;
                            if (s.ToLower() == "PhotoOfTheDay".ToLower())
                            {
                                p.Kill();
                                break;
                            }
                        }
                    }

                    this.Invoke(UpdateInfo, new Object[] { Response });
                    Thread.Sleep(500);
                }
            }

            Response = "Updating files...";
            this.Invoke(UpdateInfo, new Object[] { Response });
            //Copy update to main executable
            File.Copy(MyPath, Target);
            //Start the updated version
            Process.Start(Target);
            Finished = true;
            //self termination
            Application.Exit();

        }

        bool Finished = false;
        //Make sure user don't terminate the application by mistake
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (!Finished)
            {
                System.Windows.Forms.DialogResult DR = MessageBox.Show("Do you really want to cancle updating?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (DR == System.Windows.Forms.DialogResult.Yes)
                {
                    if (Updater.IsAlive)
                        Updater.Abort();
                    Application.Exit();
                }
                else
                {
                    e.Cancel = true;
                }
            }
            base.OnFormClosing(e);
        }

        private delegate void SetText(string s);

        private void UpdateStatus(string s)
        {
            StatusLabel.Text = s;
        }

    }
}
